#include "xlcomm/net/http/http_server.h"
using namespace xlcomm;

#include "AIGCJson-master/include/AIGCJson.hpp"

struct User {
  std::string name;
  int age;
  AIGC_JSON_HELPER(name, age);
};

void OnHttpRequest(const net::HttpRequest& req, net::HttpResponse* resp) {
  LOG_DEBUG << ">>>>method:" << req.MethodToString() << " path:" << req.path_
            << " query:" << req.query_ << " body:" << req.body_;
  if (req.method_ != net::HttpRequest::kPost) {
    resp->set_status_code(net::HttpResponse::k400BadRequest);
    return;
  }

  std::string body;
  const std::string& path = req.path_;
  if (path == "/") {
    body = "hello, I'm http server.\n";
  } else if (path == "/user") {
    User user;
    if (!aigc::JsonHelper::JsonToObject(user, req.body_)) {
      LOG_ERROR << "aigc::JsonHelper::JsonToObject User error!";
    } else {
      LOG_INFO << "user.name:" << user.name << " user.age:" << user.age;
      user.name = "nihao, " + user.name;
      user.age += 1;
      std::string json;
      if (aigc::JsonHelper::ObjectToJson(user, json)) body = json;
    }
  } else {
    body = "not support.";
  }
  resp->set_status_code(net::HttpResponse::k200Ok);
  resp->set_body(body);
}

int main() {
  Logger::SetLogLevel(Logger::kDebug);
  net::EventLoop loop;
  net::HttpServer server(&loop, net::InetAddress(8080));
  server.set_http_request_cb(std::bind(OnHttpRequest, _1, _2));
  server.Start();
  loop.Loop();
}